import copy
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from MedicineReminder.models import ReminderItem, FinishedRecord
from SecureHelperServer.settings import formatResponseData
from utils.conf import verifyID, newID, Response
from utils.custom import MyJWTAuthentication


class TakeFinishedRecord(APIView):
    # 局部(本视图有效)认证类
    authentication_classes = [MyJWTAuthentication]
    # 局部(本视图有效)权限类
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        """
        产生服药记录
        """
        data = copy.deepcopy(formatResponseData)
        try:
            nowTimeStamp = request.data.get("nowTimeStamp")
            remindItemId = request.data.get("remindItemId")

            if not (nowTimeStamp and remindItemId):
                return Response(data=data, responseMsg="请求参数缺失", loggerMsg="请求参数缺失", isError=True)

            if not verifyID(remindItemId):
                return Response(data=data, responseMsg="该提醒项不存在",
                                loggerMsg=f"产生服药记录：remindItemId={remindItemId}不是一个有效的id", isError=True)

            remindItem = ReminderItem.objects.filter(id=remindItemId, medicine__user=request.user).first()

            if not remindItem:
                return Response(data=data, responseMsg="该提醒项不存在",
                                loggerMsg=f"产生服药记录：未找到remindItemId={remindItemId}对应的提醒项", isError=True)

            FinishedRecord(id=newID(), timeStamp=nowTimeStamp, reminderItem=remindItem).save()

            return Response(data=data, responseMsg="记录成功", loggerMsg=f"产生服药记录: 成功，uid={request.user.uid}")

        except Exception as e:
            return Response(data=data, responseMsg="ServerError",
                            loggerMsg=f"请求处理失败: {e}", isError=True)
